//
//  AppManager.m
//  AAPowerApp
//
//  Created by 李恺然 on 2018/11/25.
//  Copyright © 2018 Karl. All rights reserved.
//

#import "AppManager.h"
#import "AppDelegate.h"
#import "LoginVC.h"
#import "ConfigModel.h"
#import "YYModel.h"

static NSString *configURLString = @"http://aa.mysmartedu.com.cn/index.php/User/Login/loginapi";
static NSString *loginURLString = @"https://aa.mysmartedu.com.cn/index.php/user/login/dologin/app/1";
static NSString *logoutURLString = @"https://aa.mysmartedu.com.cn/index.php/Question/logout";
static NSString * appowerDomain = @"https://aa.mysmartedu.com.cn/";
static NSString * kUserLanguageStoreKey = @"kUserLanguageStoreKey";

@interface AppManager()<NSURLSessionDataDelegate>
@property (nonatomic) NSURLSession *session;
@end

@implementation AppManager

+ (instancetype)sharedManager{
    static AppManager *sharedManager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager = [[AppManager alloc] init];
    });
    return sharedManager;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _userLanguage = [self getCurrentUserLanguage];
    }
    return self;
}

- (void)fetchConfigWithCompetedHandler:(void (^)(NSError *))completedHandler{
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    NSURL *url = [NSURL URLWithString:configURLString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    NSURLSessionDataTask *tast = [_session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
           
           if (error != nil) {
               completedHandler(error);
           }else{
               NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
               ConfigModel *config = [ConfigModel yy_modelWithJSON:dic[@"data"]];
               [config cacheConfig];
               self.config = config;
               completedHandler(nil);
           }
       }];
       [tast resume];
}

- (NSString *)getLoginUrlString{
    
    if (self.config) {
        switch (_userLanguage) {
            case UserLanguageEng:
                return self.config.login_url_en;
            case UserLanguageChn:
                return self.config.login_url_cn;
        }
    }
    return loginURLString;
}

- (void)loginWithUserName:(NSString *)userName psw:(NSString *)psw competedHandler:(void (^)(NSError *))completedHandler{
    if (userName.length == 0 ||
        psw.length == 0) {
        NSError *error = [NSError errorWithDomain:@"AppManager" code:0 userInfo:@{NSLocalizedDescriptionKey:@"Incorrect ID or password!",NSLocalizedFailureReasonErrorKey:@"Incorrect ID or password!"}];
        completedHandler(error);
        return;
    }
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];

    _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
    NSURL *loginURL = [NSURL URLWithString:[self getLoginUrlString]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:loginURL];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [[NSString stringWithFormat:@"username=%@&password=%@",userName,psw] dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSessionDataTask *tast = [_session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (error != nil) {
            completedHandler(error);
        }else{
            
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
            if (dic && !error && [dic[@"status"] isEqualToString:@"success"]) {
                NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
                [ud setObject:userName.copy forKey:@"username"];
                [ud setObject:psw.copy forKey:@"password"];
                [ud synchronize];
                [self storeCookieString];
                completedHandler(nil);
            }else{
                completedHandler([NSError errorWithDomain:@"AppManager" code:1 userInfo:@{NSLocalizedDescriptionKey:@"Incorrect ID or password!",NSLocalizedFailureReasonErrorKey:@"Incorrect ID or password!"}]);
            }
        }
    }];
    [tast resume];
}

- (void)autoLoginWithCompetedHandler:(void (^)(NSError *))completedHandler{
    [self loginWithUserName:self.userName
                        psw:self.psw
            competedHandler:completedHandler];
}

- (void)logoutWithCompetedHandler:(void (^)(NSError *))completedHandler{
    _userName = @"";
    _psw = @"";
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:@"" forKey:@"username"];
    [ud setObject:@"" forKey:@"password"];
    [ud synchronize];
    _cookieStr = @"";
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    LoginVC *loginVC = [[LoginVC alloc] init];
    [delegate.window setRootViewController:loginVC];
}

- (NSString *)storeCookieString{
    NSHTTPCookieStorage*cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSArray<NSHTTPCookie *> *cookies = [cookieJar cookiesForURL:[NSURL URLWithString:appowerDomain]];
    NSMutableString * cookieString = [[NSMutableString alloc]init];
    for (NSHTTPCookie*cookie in cookies) {
        [cookieString appendFormat:@"%@=%@;",cookie.name,cookie.value];
    }
    if (cookieString.length == 0) {
        self.cookieStr = cookieString;
        return nil;
    }
    
    [cookieString deleteCharactersInRange:NSMakeRange(cookieString.length - 1, 1)];
    NSLog(@"%@",cookieString);
    self.cookieStr = cookieString;
    return cookieString;
}

- (void)setCookieStr:(NSString *)cookieStr{
    _cookieStr = cookieStr;
    [[NSUserDefaults standardUserDefaults] setObject:_cookieStr forKey:@"cookieString"];
}

- (NSString *)userName{
    if (_userName.length == 0 || !_userName) {
        _userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"username"] ? :@"";
    }
    return _userName;
}

- (NSString *)psw{
    if (_psw.length == 0 || !_psw) {
        _psw = [[NSUserDefaults standardUserDefaults] objectForKey:@"password"] ? : @"";
    }
    return _psw;
}

#pragma NSURLSessionDataDelegate
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
    didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
    completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler {
    // 1.判断接收服务器挑战的方法是否是信任证书
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        // 2.如果你信任证书,就从受保护空间里面拿出证书,回调给服务器,告诉服务,我信任你,你给我发送数据吧.
        NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
        // 3.把证书回调出去
        completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
    }
}

- (ConfigModel *)config{
    if (!_config) {
        _config = [ConfigModel cachedConfig];
    }
    return _config;
}

- (void)setUserLanguage:(UserLanguage)userLanguage{
    _userLanguage = userLanguage;
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:@(_userLanguage) forKey:kUserLanguageStoreKey];
    [ud synchronize];
}

- (UserLanguage)getCurrentUserLanguage{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSNumber *lanN = [ud objectForKey:kUserLanguageStoreKey];
    UserLanguage lan = UserLanguageEng;
    if (lanN) {
        lan = [lanN integerValue];
    }
    return lan;
}

@end
